<template>
  <div class="activity-detail-container">
    <!-- Hero section with activity image and main info -->
    <div
      class="hero-section"
      :style="`background-image: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.7)), url(${detailData.cover})`"
    >
      <div class="container">
        <div class="hero-content">
          <div class="status-badge">
            <el-tag
              :type="statusMap[detailData.status]?.type || 'info'"
              effect="dark"
              size="large"
            >
              {{ statusMap[detailData.status]?.text || "未知状态" }}
            </el-tag>
          </div>
          <h1 class="activity-title">{{ detailData.title }}</h1>
          <div class="activity-meta">
            <div class="meta-item">
              <el-icon><Collection /></el-icon>
              <span>分类：{{ detailData.categoryName }}</span>
            </div>
            <div class="meta-item">
              <el-icon><User /></el-icon>
              <span>参与人数：{{ detailData.registerCount }}</span>
            </div>
          </div>
          <div class="action-buttons">
            <button
              class="register-btn pulse"
              @click="handleActivitySignup(detailData)"
            >
              立即报名
            </button>
            <div class="secondary-actions">
              <button class="action-btn wishlist" @click="addToWish()">
                <el-icon><Star /></el-icon>
                <span>加入心愿单 ({{ detailData.wishCount }})</span>
              </button>
              <button class="action-btn collect" @click="addToCollection()">
                <el-icon><Share /></el-icon>
                <span>收藏 ({{ detailData.collectCount }})</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Content section with tabs -->
    <div class="content-section">
      <div class="container">
        <div class="content-grid">
          <div class="main-content">
            <div class="tab-navigation">
              <el-radio-group v-model="radio" size="large">
                <el-radio-button
                  @click="onTagChange('简介')"
                  value="简介"
                  class="tab-button"
                  >简介</el-radio-button
                >
                <el-radio-button
                  @click="onTagChange('评论')"
                  value="评论"
                  class="tab-button"
                  >评论</el-radio-button
                >
              </el-radio-group>
            </div>

            <!-- About tab -->
            <div
              class="tab-content description"
              :class="radio != '评论' ? 'active' : ''"
            >
              <div class="description-content">
                <p>{{ detailData.description }}</p>
              </div>
            </div>

            <!-- Comments tab -->
            <div
              class="tab-content comments"
              :class="radio == '评论' ? 'active' : ''"
            >
              <div class="comments-wrapper">
                <div class="new-comment-section">
                  <h3>发表新的评论</h3>
                  <div class="comment-form">
                    <el-avatar
                      class="user-avatar"
                      src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                    />
                    <div class="input-group">
                      <el-select
                        v-model="appraise"
                        placeholder="评价"
                        size="large"
                        class="rating-select"
                      >
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-input
                        v-model="commentInput"
                        placeholder="说点什么..."
                        class="comment-input"
                      />
                    </div>
                    <el-button
                      type="primary"
                      size="large"
                      @click="sendComment()"
                      class="send-comment-btn"
                      >发送</el-button
                    >
                  </div>
                </div>

                <div class="comments-header">
                  <div class="comments-count">
                    共有 {{ pagination.total }} 条评论
                  </div>
                  <div class="comments-sort" v-if="commentData.length > 0">
                    <span
                      :class="[
                        'sort-option',
                        sortIndex == 'recent' ? 'active' : '',
                      ]"
                      @click="sortCommentList('recent')"
                      >最新</span
                    >
                    <div class="sort-divider"></div>
                    <span
                      :class="[
                        'sort-option',
                        sortIndex != 'recent' ? 'active' : '',
                      ]"
                      @click="sortCommentList('hot')"
                      >热门</span
                    >
                  </div>
                </div>

                <div class="comments-list">
                  <div
                    class="comment-card"
                    v-for="item in commentData"
                    :key="item.id"
                  >
                    <div class="comment-header">
                      <div class="user-info">
                        <el-avatar class="user-avatar" :src="item.avatar" />
                        <div class="user-details">
                          <div class="username">{{ item.username }}</div>
                          <div class="comment-time">{{ item.commentTime }}</div>
                        </div>
                      </div>
                      <div class="comment-actions">
                        <div
                          class="rating-badge"
                          :class="{
                            good: item.commentLevel == '1',
                            neutral: item.commentLevel == '2',
                            bad: item.commentLevel == '3',
                          }"
                        >
                          {{
                            item.commentLevel == "1"
                              ? "好评"
                              : item.commentLevel == "2"
                                ? "中评"
                                : "差评"
                          }}
                        </div>
                        <div class="like-button" @click="likeComment(item.id)">
                          <el-icon><CaretTop /></el-icon>
                          <span>{{ item.likeCount }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="comment-body">
                      <p>{{ item.content }}</p>
                    </div>
                  </div>

                  <!-- Pagination -->
                  <div class="pagination-container">
                    <el-pagination
                      :page-sizes="[2, 5, 20, 40, 50, 100]"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="pagination.total"
                      :default-page-size="pagination.size"
                      @change="onPaginationChange"
                      background
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="sidebar">
            <div class="recommendations">
              <span class="dot"></span>
              <h3>相似活动推荐</h3>
              <p class="section-description">你可能还喜欢这些活动</p>
              <div class="recommendation-list">
                <div
                  class="recommendation-card"
                  v-for="item in recommendData"
                  :key="item.id"
                  @click="handleDetail(item)"
                >
                  <div class="recommendation-image">
                    <img :src="item.cover" alt="活动封面" />
                  </div>
                  <div class="recommendation-info">
                    <h4>{{ item.title }}</h4>
                    <div class="participant-count">
                      <el-icon><User /></el-icon>
                      <span>已报名人数: {{ item.registerCount }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Registration Dialog -->
  <el-dialog
    v-model="activitySignupDeatailDialog.isVisible"
    width="80%"
    center
    destroy-on-close
    class="custom-dialog"
  >
    <ActivitySignupDetail :pageData="activitySignupDetail" />
    <template #footer>
      <div class="dialog-footer">
        <el-button
          @click="handleCommitActivitySignup(activitySignupDetail)"
          type="success"
          size="large"
          class="confirm-button"
          :disabled="detailData.status !== 1"
        >
          <el-icon><Check /></el-icon> 立即报名
        </el-button>
        <el-button size="large" @click="handleBack" class="cancel-button">
          <el-icon><Close /></el-icon> 取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  activityPage,
  activityGetById,
  baseItemRecommend,
} from "@/apis/activity";
import {
  commentPage,
  commentGetById,
  commentAdd,
  commentEdit,
} from "@/apis/user/comment";
import { getFormatTime } from "@/apis/utility";
import {
  Star,
  Share,
  Collection,
  User,
  CaretTop,
  Check,
  Close,
} from "@element-plus/icons-vue";
import { wishGetById, wishEdit, wishAdd } from "@/apis/user/wish";
import {
  collectGetById,
  collectEdit,
  collectAdd,
} from "@/apis/user/collection";
import { watchEffect } from "vue";
import { activitySignupAdd } from "@/apis/user/activity-signup";
import ActivitySignupDetail from "./ActivitySignupDetail.vue";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const router = useRouter();
// 活动数据
const detailData = ref({});

// 根据活动ID查询活动
const getActivityById = async (id) => {
  const result = await activityGetById(id);
  if (result != undefined) {
    detailData.value = result.data;
  }
};

// 活动状态
const statusMap = {
  0: { text: "未发布", type: "info" },
  1: { text: "已发布", type: "success" },
  2: { text: "签到中", type: "warning" },
};

// 评论数据
const commentData = ref([]);

// 过滤对应的条件
const filter = reactive({
  activityId: route.params.activityId,
});

// 搜索输入框搜索条件
const search = reactive({});

// 过滤对应的选项
const filterOptions = reactive({});

// 存储排序字段
const orders = reactive({
  column: "id",
  isAsc: true,
});

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});
/**
 * 分页改变函数
 * @param {*} currentPage 当前页
 * @param {*} pageSize 每页条数
 */

const onPaginationChange = (currentPage, pageSize) => {
  pagination.page = currentPage;
  pagination.size = pageSize;
  getComments();
};

// 获取所有评论
const getComments = () => {
  commentPage(
    {
      filter: filter,
      search: search,
      orders: [orders],
    },
    pagination.page,
    pagination.size
  ).then((result) => {
    commentData.value = result.data.records;
    pagination.total = result.data.total;
  });
};

// 实现标签切换
let radio = ref("简介");

// 点击标签页的触发函数
const onTagChange = (key) => {
  if (key != "评论") {
    radio.value = "简介";
  } else {
    radio.value = "评论";
  }
  getComments();
};

// 评论输入框
const options = [
  {
    value: "1",
    label: "好评",
  },
  {
    value: "2",
    label: "中评",
  },
  {
    value: "3",
    label: "差评",
  },
];

const commentInput = ref("");
// 默认好评
const appraise = ref("1");
// 发送评论
const newComment = ref({
  activityId: route.params.activityId,
  content: commentInput,
  commentLevel: appraise,
});

// 发送评论
const sendComment = async () => {
  if (newComment.value.content.length > 0) {
    await commentAdd(newComment.value).then((result) => {});
    getComments();
  }
};

// 得到该评论其他字段
const updateComment = ref();

// 喜欢评论
const likeComment = async (id) => {
  try {
    // 等待获取评论信息完成
    const result = await commentGetById(id);
    // 更新评论信息
    updateComment.value = result.data;
    // 点赞次数加1
    updateComment.value.likeCount++;
    // 保存更新后的评论信息
    const editResult = await commentEdit(updateComment.value);
  } catch (error) {
    console.error("点赞过程中发生错误:", error);
  }
  // 操作成功后调用getComments刷新评论列表
  getComments();
};

// 相似活动推荐数据

// 评论排序
const sortIndex = ref({});
const sortCommentList = (method) => {
  if (method == "recent") {
    sortIndex.value = "recent";
    orders.column = "comment_time";
    orders.isAsc = false;
    getComments();
  } else {
    sortIndex.value = "hot";
    // 将字符串比较转化为数值型比较
    orders.column = "CAST(like_count AS UNSIGNED)";
    orders.isAsc = false;
    getComments();
  }
};

// 加入收藏单
// 收藏数据
const collectionData = reactive({});
const addToCollection = async () => {
  const id = route.params.activityId;
  collectionData.activityId = id;
  await collectAdd(collectionData).then(() => {});
  getActivityById(id);
};

// 加入心愿单
// 心愿数据
const wishData = reactive({});
const addToWish = async () => {
  const id = route.params.activityId;
  wishData.activityId = id;
  await wishAdd(wishData).then(() => {});
  getActivityById(id);
};

// 相似活动推荐
const recommendData = ref([]);

const getBaseItem = async () => {
  const result = await baseItemRecommend();
  recommendData.value = result.data;
};

// 跳转活动详情页
const handleDetail = (item) => {
  router.push({
    name: "activityDetail",
    params: { activityId: item.id },
  });
};

// 监听路由变化
watchEffect(async () => {
  const id = route.params.activityId;
  getActivityById(id);
  filter.activityId = id;
  getComments();
  getBaseItem();
});

// 实现报名活动功能
const getAddActivitySignup = async (value) => {
  await activitySignupAdd(value);
};
// 触发报名活动功能
const handleActivitySignup = async (item) => {
  activitySignupDetail.value = item;
  activitySignupDetailVisible();
};

const activitySignupDetail = ref({});

/**
 * 报名活动详情对话框
 */
const activitySignupDeatailDialog = reactive({
  isVisible: false,
});
// 控制对话框是否显示
const activitySignupDetailVisible = () => {
  activitySignupDeatailDialog.isVisible = true;
};

// 发起报名活动
const handleCommitActivitySignup = async () => {
  console.log(activitySignupDetail.value);
  // activitySignupDetail.value.status = 1;
  confirmSignup();
};

// 关闭对话框
const handleBack = () => {
  activitySignupDeatailDialog.isVisible = false;
};
// 确认报名消息
const confirmSignup = async () => {
  ElMessageBox.confirm("进行报名", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await getAddActivitySignup(activitySignupDetail.value);
      activitySignupDeatailDialog.isVisible = false;
    })
    .catch(async () => {
      activitySignupDetail.status = 2;
      await getAddActivitySignup(activitySignupDetail.value);
      activitySignupDeatailDialog.isVisible = false;
    });
};
</script>

<style scoped>
/* Base styles */
.activity-detail-container {
  font-family: "Helvetica Neue", Arial, sans-serif;
  color: #333;
  background-color: #f8f9fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

/* Hero section */
.hero-section {
  background-size: cover;
  background-position: center;
  position: relative;
  color: white;
  padding: 80px 0;
  margin-bottom: 30px;
}

.hero-content {
  max-width: 800px;
}

.status-badge {
  margin-bottom: 16px;
}

.activity-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 16px;
  line-height: 1.2;
}

.activity-meta {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1rem;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.register-btn {
  background: linear-gradient(45deg, #ff6b6b, #ff8e53);
  color: white;
  border: none;
  padding: 16px 32px;
  font-size: 1.125rem;
  font-weight: 600;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
  max-width: 200px;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
}

.pulse {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(255, 107, 107, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0);
  }
}

.secondary-actions {
  display: flex;
  gap: 16px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 8px 16px;
  border-radius: 6px;
  color: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* Content section */
.content-section {
  padding-bottom: 60px;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 30px;
}

@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: 1fr;
  }
}

.main-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.tab-navigation {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.tab-button {
  font-weight: 500;
}

.tab-content {
  display: none;
  padding: 24px;
}

.tab-content.active {
  display: block;
}

.description-content {
  font-size: 1rem;
  line-height: 1.7;
  color: #555;
}

/* Comments section */
.comments-wrapper {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.new-comment-section h3 {
  margin-bottom: 16px;
  font-size: 1.25rem;
  font-weight: 600;
}

.comment-form {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.user-avatar {
  flex-shrink: 0;
}

.input-group {
  display: flex;
  flex-grow: 1;
  gap: 8px;
}

.rating-select {
  width: 110px;
}

.comment-input {
  flex-grow: 1;
}

.send-comment-btn {
  flex-shrink: 0;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 0;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.comments-count {
  font-weight: 500;
  color: #666;
}

.comments-sort {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sort-option {
  cursor: pointer;
  color: #666;
  transition: color 0.2s ease;
}

.sort-option:hover {
  color: #1890ff;
}

.sort-option.active {
  color: #1890ff;
  font-weight: 500;
}

.sort-divider {
  width: 1px;
  height: 14px;
  background-color: #ddd;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-card {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.2s ease;
}

.comment-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  background: #f5f5f5;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
}

.comment-time {
  font-size: 0.875rem;
  color: #999;
}

.comment-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.rating-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
}

.rating-badge.good {
  background-color: #f0f9eb;
  color: #67c23a;
}

.rating-badge.neutral {
  background-color: #f4f4f5;
  color: #909399;
}

.rating-badge.bad {
  background-color: #fef0f0;
  color: #f56c6c;
}

.like-button {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  color: #666;
  transition: all 0.2s ease;
}

.like-button:hover {
  color: #1890ff;
}

.comment-body {
  font-size: 0.95rem;
  line-height: 1.6;
  color: #444;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* Sidebar */
.sidebar {
  align-self: start;
  position: sticky;
  top: 20px;
}

.recommendations {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 24px;
}

.recommendations h3 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  padding-bottom: 0px;
}

.recommendation-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.recommendation-card {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.2s ease;
  cursor: pointer;
}

.recommendation-card:hover {
  background-color: #f5f5f5;
}

.recommendation-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
}

.recommendation-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.recommendation-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.recommendation-info h4 {
  font-size: 0.95rem;
  font-weight: 500;
  margin: 0;
  color: #333;
  line-height: 1.4;
  /* Limit to 2 lines with ellipsis */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.participant-count {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.8rem;
  color: #999;
}

/* Dialog */
.custom-dialog :deep(.el-dialog__header) {
  padding: 20px 24px;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.confirm-button,
.cancel-button {
  min-width: 120px;
}

@media (max-width: 768px) {
  .hero-section {
    padding: 40px 0;
  }

  .activity-title {
    font-size: 1.75rem;
  }

  .activity-meta {
    flex-direction: column;
    gap: 12px;
  }

  .comment-form {
    flex-direction: column;
  }

  .input-group {
    flex-direction: column;
  }

  .secondary-actions {
    flex-direction: column;
  }
}

.section-description {
  font-size: 14px;
  color: #86868b;
  border-bottom: 2px solid #f5f5f5;
}

.dot {
  width: 10px;
  height: 10px;
  background: #0066cc;
  border-radius: 50%;
  box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.2);
}
</style>
